package com.alibaba.user.service.impl;

import com.alibaba.basic.constant.VerifyCodeConstants;
import com.alibaba.basic.dto.BinderDto;
import com.alibaba.basic.exception.BusinessException;
import com.alibaba.basic.jwt.JwtUtils;
import com.alibaba.basic.jwt.LoginData;
import com.alibaba.basic.jwt.RsaUtils;
import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.basic.util.AjaxResult;
import com.alibaba.basic.util.HttpUtil;
import com.alibaba.basic.util.MD5Utils;
import com.alibaba.basic.util.StrUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.system.domain.Menu;
import com.alibaba.user.constant.WxConstants;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.domain.User;
import com.alibaba.user.domain.Wxuser;
import com.alibaba.user.dto.LoginDto;
import com.alibaba.user.mapper.LogininfoMapper;
import com.alibaba.user.mapper.UserMapper;
import com.alibaba.user.mapper.WxuserMapper;
import com.alibaba.user.service.ILogininfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：登录
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 账号登录
     * @param loginDto
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String inputPassword = loginDto.getPassword();
        Integer loginType = loginDto.getLoginType();
        // 1. 校验：空值校验
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(inputPassword) || StringUtils.isEmpty(loginType)) {
            throw new BusinessException("数据不能为空");
        }

        // 2. 校验：校验账号是否为空
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo == null) {
            throw new BusinessException("账号为空，请注册后登录");
        }

        // 3. 校验：校验密码是否正确
        String md5Password = MD5Utils.encrypByMd5(inputPassword + logininfo.getSalt());
        if (!md5Password.equals(logininfo.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }

        // 4. 校验：校验账号是否启用
        if (!logininfo.getDisable()) {
            throw new BusinessException("账号已被禁用，请联系管理员");
        }

        /*// 5. 将token和登录信息保存到redis中，设置30分钟有效
        // 生成key
        String token = UUID.randomUUID().toString();
        // 设置登录信息的盐值和密码为空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);

        // 6. 使用map保存token和登录信息传递给前端
        Map<String, Object> map = new HashMap<>();

        // 将信息保存到map中
        map.put("token", token);
        map.put("logininfo", logininfo);*/

        // 登录成功后返回map保存登录信息、权限和菜单
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return map;
    }

    /**
     * 微信登录
     * @param code
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String code) {
        // 1. 根据code发送请求获取token和openid
        String url = WxConstants.GET_ACK_URL
                .replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        String jsonStr = HttpUtil.httpGet(url);

        // 2. 将响应的json字符串转成json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        // 获取token和openid
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        // 3. 通过openid去t_wxuser中查询对象
        Wxuser wxuser = wxuserMapper.loadByOpenId(openid);

        if (wxuser != null && wxuser.getUserId() != null) {
            // 4. 查询到对象：有绑定过，直接免密登录
            Logininfo logininfo = logininfoMapper.LoadLogininfoByUserId(wxuser.getUserId());
            /*// 获取token
            String token = UUID.randomUUID().toString();
            logininfo.setPassword(null);
            logininfo.setSalt(null);
            // 将token和logininfo存到redis中
            redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);

            // 将token和logininfo保存起来返回给前端
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("logininfo", logininfo);*/

            // 登录成功后返回map保存登录信息、权限和菜单
            Map<String, Object> map = loginSuccessJwtHandler(logininfo);

            return AjaxResult.me().setResultObj(map);
        } else {
            // 5. 没有绑定过，将access_token和openid响应给前端，前端跳转绑定页面
            Map<String, Object> map = new HashMap<>();
            map.put("access_token", access_token);
            map.put("openid", openid);

            return AjaxResult.me().setSuccess(false).setResultObj(map);
        }
    }

    /**
     * 微信绑定
     * @param binderDto
     * @return
     */
    @Override
    public AjaxResult wechatBinder(BinderDto binderDto) {
        String phone = binderDto.getPhone();
        String inputVerifyCode = binderDto.getVerifyCode();
        String accessToken = binderDto.getAccessToken();
        String openId = binderDto.getOpenId();

        // 1. 校验：空值校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(inputVerifyCode)) {
            throw new BusinessException("数据不能为空");
        }
        // 2. 校验：校验验证码是否过期 9527:1456666660000
        Object redisCode = redisTemplate.opsForValue().get(VerifyCodeConstants.BINDER_PREFIX + phone);
        if (redisCode == null) {
            throw new BusinessException("验证码失效");
        }

        // 3. 校验：校验验证码是否正确
        if (!redisCode.toString().split(":")[0].equalsIgnoreCase(inputVerifyCode.trim())) {
            throw new BusinessException("验证码错误");
        }

        // 绑定：绑定到t_wxuser和t_user
        // 4. 通过发送第三个请求获取Wxuser
        String url = WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        // 发送请求，返回一个json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        // 将json格式的字符串转换为json对象
        Wxuser wxuser = json2Wxuser(jsonStr);

        // 5. 通过输入的手机号查询user
        User user = userMapper.loadByPhone(phone);

        // 6. 判断user是否为空，如果为空则根据phone创建user对象，先添加logininfo，再添加user
        if (user == null) { // user为空
            // 根据手机号创建user对象
            user = phone2User(phone);
            // 将user的信息添加到t_logininfo表中
            Logininfo logininfoTemp = user2Logininfo(user);
            logininfoMapper.add(logininfoTemp);

            // 设置t_user表的logininfoId
            user.setLogininfoId(logininfoTemp.getId());
            userMapper.add(user);
        }
        // 7. 绑定wxuser和user：将user的id设置到wxuser对象中
        wxuser.setUserId(user.getId());
        // 8. 将wxuser添加到数据库
        wxuserMapper.add(wxuser);

        // 9. 做免密登录：指redis中含有登录信息
        // 根据user的logininfoId查询Logininfo
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());
        /*// 获取redis中的token
        String token = UUID.randomUUID().toString();
        // 将登录信息的盐值和密码设置为空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        // 将登录信息添加到redis中,并设置30分钟有效期
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
        // 将token和logininfo返回给前端
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);*/

        // 登录成功后返回map保存登录信息、权限和菜单
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setResultObj(map);
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        // 1. 获取logininfo
        // 设置到loginData中
        LoginData loginData = new LoginData();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        loginData.setLogininfo(logininfo);
        Map<String, Object> map = new HashMap<>();

        try {
            // 判断是否是管理员，如果是管理员则获取权限和菜单
            if (logininfo.getType() == 0) {
                // 2. 获取当前登录人的permissions
                List<String> permissions = logininfoMapper.loadPermissionsByLogininfoId(logininfo.getId());
                // 3. 获取当前登录人的menus
                List<Menu> menus = logininfoMapper.loadMenusByLogininfoId(logininfo.getId());

                // 设置权限到loginData对象中
                loginData.setPermissions(permissions);
                // 设置菜单到loginData对象中
                loginData.setMenus(menus);

                // 将permissions和menus添加到map中返回给前端
                map.put("permissions", permissions);
                map.put("menus", menus);

            }
            // 4. 通过私钥对登录信息进行加密生成jwtToken字符串
            // 获取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            // 使用私钥加密获取JwtToken
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);

            // 5. 将信息设置到map中，返回到前端
            map.put("token", jwtToken);
            map.put("logininfo",logininfo);

            return map;

        } catch (Exception e) {
            e.printStackTrace();
        }
            return null;
    }

    /** 账号退出 */
    @Override
    public void logout(String token) {
        // 清空redis
        redisTemplate.delete(token);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        // 生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 生成随机数字密码
        String randomPwd = StrUtils.getRandomString(6);
        // 对随机密码进行加密
        String md5Password = MD5Utils.encrypByMd5(randomPwd + salt);
        // 设置盐值到user对象中
        user.setSalt(salt);
        // 设置随机密码到user对象中
        user.setPassword(md5Password);
        return user;
    }

    private Wxuser json2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        // 将json格式字符串转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        // 设置wxuser的openid
        wxuser.setOpenid(jsonObject.getString("openid"));
        // 设置wxuser的Nickname
        wxuser.setNickname(jsonObject.getString("nickname"));
        // 设置wxuser的sex
        wxuser.setSex(jsonObject.getInteger("sex"));
        // 设置wxuser的address
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        // 设置wxuser的headimgurl
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        // 设置wxuser的unionid
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;

    }
}
